<template>
  <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="form">
    <el-form-item prop="phone" v-show="phoneOrEmail.name === 'phone'">
      <el-row>
        <el-col :span="7">
          <el-select v-model="countrycode">
            <el-option-group
              v-for="group in countrycodes"
              :key="group.label"
              :label="group.label"
            >
              <el-option
                v-for="item in group.countryList"
                :key="item.code"
                :value="item.code"
              >
                <span style="float: left">{{ item.zh }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{
                  item.code
                }}</span>
              </el-option>
            </el-option-group>
          </el-select>
        </el-col>
        <el-col :span="16" :offset="1">
          <el-input placeholder="网易云音乐手机号" v-model="loginForm.phone"></el-input>
        </el-col>
      </el-row>
    </el-form-item>
    <!-- 切换显示状态 -->
    <el-form-item prop="email" v-show="phoneOrEmail.name === 'email'">
      <el-input placeholder="邮箱" v-model="loginForm.email"></el-input>
    </el-form-item>
    <el-form-item
      :error="errPassword"
      prop="password"
      style="margin-bottom:0px"
    >
      <el-input
        :type="showPassword"
        placeholder="密码"
        v-model="loginForm.password"
      >
        <template slot="append">
          <div class="icon-wrap" @click.stop="toggleType">
            <i class="iconfont icon-eye"></i>
          </div>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item style="margin-bottom:0px">
      <el-button type="text" class="forget-password">忘记密码? 嘿嘿,我这没有</el-button>
    </el-form-item>
    <el-form-item>
      <el-button class="login-btn" @click.stop="login">登录</el-button>
    </el-form-item>
    <el-form-item class="footer-tips">
      <span
        >没有神马音乐账户,
        <span
          class="toRegistry"
          @click.stop="mode = 'registry'"
          @click="toRegistry"
          >快速注册</span
        ></span
      >
    </el-form-item>
  </el-form>
</template>
<script>
import countrycodes from '@/utlis/countrycodes'
import { setUserId, setToken } from '@/utlis/storage'
import { userLogin } from '@/api/registry_login'
import { mapMutations } from 'vuex'
export default {
  inject: ['phoneOrEmail'],
  data () {
    return {
      // 错误密码
      errPassword: '',
      // 国家码列表
      countrycodes,
      // 是否显示密码
      showPassword: 'password',
      // 国家码
      countrycode: '86',
      // 表单数据
      loginForm: {
        phone: null,
        email: null,
        password: null
      },
      // 表单规则
      loginRules: {
        phone: [
          { required: true, message: '手机号填一填拉', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              const _phone = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
              if (_phone.test(value)) {
                callback()
              } else {
                callback(new Error('手机号码格式不正确'))
              }
            },
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '密码也填一填拉', trigger: 'blur' },
          {
            min: 6,
            max: 20,
            message: '请输入 6 ~ 20 位密码',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              const _email = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
              if (_email.test(value)) {
                callback()
              } else {
                callback(new Error('邮箱格式不正确'))
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    ...mapMutations(['SETUSERINFO']),
    // 触发父方法
    toRegistry () {
      this.$emit('setMode', 'registry')
    },
    // 登录
    async login () {
      if (this.phoneOrEmail.name === 'phone') {
        let phoneNum = 0
        this.$refs.loginForm.validateField(['phone', 'password'], error => {
          if (error === '') {
            phoneNum++
          }
        })
        if (phoneNum === 2) {
          try {
            delete this.loginForm.email
            const data = await userLogin(this.loginForm)
            window.console.log(data)
            if (data.code === 200) {
              this.$message.success('欢迎回来!')
              setUserId(data.profile.userId)
              setToken(data.token)
              this.SETUSERINFO(data.profile)
              // 关闭dialog
              this.$emit('loginDone')
            } else {
              this.errPassword = '1'
              this.$nextTick(() => {
                this.errPassword = data.message
              })
            }
          } catch (error) {
            window.console.log(error)
          }
        }
      } else {
        let emailNum = 0
        this.$refs.loginForm.validateField(['email', 'password'], error => {
          if (error === '') {
            emailNum++
          }
        })
        if (emailNum === 2) {
          this.$message.success('验证通过')
          console.log(this.loginForm)
        }
      }
    },
    // 切换输入框类型
    toggleType () {
      if (this.showPassword === 'password') {
        this.showPassword = 'text'
      } else if (this.showPassword === 'text') {
        this.showPassword = 'password'
      }
    }
  }
}
</script>
<style lang="less" scoped>
.el-select-group .el-select-dropdown__item {
  padding: 0 20px;
}
.form {
  width: 330px;
  margin: 0 auto;
  /deep/ .el-input-group__append {
    padding: 0;
    position: relative;
    width: 50px;
    cursor: pointer;
    .icon-wrap {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    &:hover {
      background-color: #eeeeee;
    }
  }
  .forget-password {
    color: #cccccc;
    width: 100%;
    text-align: right;
    &:hover {
      color: @main-font-color;
    }
  }
  .login-btn {
    width: 100%;
    background-color: #333333;
    color: @main-font-color;
    &:hover {
      background-color: #5c5c5c;
    }
  }
  .footer-tips {
    text-align: center;
    .toRegistry {
      cursor: pointer;
      color: @main-font-color;
      &:hover {
        color: #333;
      }
    }
  }
}
</style>
